package com.ruoyi.thread.service;

import com.ruoyi.thread.entity.*;
import com.ruoyi.thread.entity.init.DataInitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 综合性的CompleteFuture 服务
 */
@Service
@Slf4j
public class ThreadO2Service {

    @Autowired
    DataInitService dataInitService;
    /**
     * 基本信息:最近5个订单,未读消息,用户统计,推荐商品
     * 然后合并成 UserDashboard 对象。
     */
    @Async
    public CompletableFuture<UserDashboard> getUserDashboard(Long userId) {
        dataInitService.initData();
        //1.获取前五个订单
        CompletableFuture<List<Order>> orderList = CompletableFuture.supplyAsync(() ->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return dataInitService.getOrders().stream().limit(5).collect(Collectors.toList());
            }

        );
        // 2.获取未读消息
        CompletableFuture<List<Message>> messageList = CompletableFuture.supplyAsync(() ->
                dataInitService.getMessages().stream().filter(message -> !message.getRead()).collect(Collectors.toList()));
        //3.获取用户统计
        CompletableFuture<List<User>> users = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return dataInitService.getUsers();

        });
        //4.推荐商品
        CompletableFuture<List<Product>> productList = CompletableFuture.supplyAsync(() -> dataInitService.getProducts().stream()
                .filter(product -> product.getStatus().equals(Product.ProductStatus.ON_SALE))
                .collect(Collectors.toList()));
        CompletableFuture.allOf(orderList, messageList, users, productList).join();
        UserDashboard userDashboard = new UserDashboard(users.join().get(0),
                orderList.join(),
                messageList.join(),
                null,
                productList.join());
        return CompletableFuture.completedFuture(userDashboard);

    }

}
